package com.atguigu.gmall.seckill.service.impl;

import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.seckill.mapper.SecKillGoodsMapper;
import com.atguigu.gmall.seckill.service.SeckillGoodsService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/17 20:00 星期一
 * description:
 */
@Service
@Log4j2
@Transactional(rollbackFor = Exception.class)
public class SeckillGoodsServiceImpl implements SeckillGoodsService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询指定时间段的商品的列表
     *
     * @param time
     * @return
     */
    @Override
    public List<SeckillGoods> getSeckillGoodsList(String time) {
        return redisTemplate.opsForHash().values(time);
    }

    /**
     * 查询指定时间段的指定商品
     *
     * @param goodsId
     * @param time
     * @return
     */
    @Override
    public SeckillGoods getSeckillGoods(String goodsId, String time) {
        return (SeckillGoods) redisTemplate.opsForHash().get(time,goodsId);
    }

    @Resource
    private SecKillGoodsMapper secKillGoodsMapper;
    /**
     * 同步秒杀商品的库存到数据库中去
     *
     * @param time
     */
    @Override
    public void updateSeckillGoodsStock(String time) {
        //获取指定时间段的全部的商品的数据和库存的数据
        Set<String> goodsIds = redisTemplate.opsForHash().keys("Seckill_Goods_Stock_" + time);
        //System.out.println("keys =" +keys);
        //逐个的进行数据同步
        goodsIds.stream().forEach(goodsId -> {
           //获取剩余库存
            Object o = redisTemplate.opsForHash().get("Seckill_Goods_Stock_" + time, goodsId);
            //同步库存
            int i = secKillGoodsMapper.updateSeckillGoodsStock(Long.valueOf(goodsId), Integer.parseInt(o.toString()));
            if(i < 0){
                //数据同步失败,需要将失败的信息记录到日志中去!!!!
                log.error("商品库存同步失败,商品的id为:" + goodsId + ",商品应该同步的库存为:" + o.toString());
            }
            //数据同步成功,需要清理redis中的库存数据
            redisTemplate.opsForHash().delete("Seckill_Goods_Stock_" + time, goodsId);
        });
    }
}
